LeetCode Js-88. Merge Sorted Array
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1.
To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored.
nums2 has a length of n.
你給予兩個整數陣列 nums1 和 nums2,兩個整數 m 和 n 分別代表 nums1 和 nums2 的元素個數。
合併 nums1 和 nums2 成為一個「非遞減」的訂單排序,不過是新增到 nums1 中。
關於這個狀況,nums1 有一個長度是 m + n,而前面的 m 元素表示為被合併,後面的 n 元素是變為 0 並忽略。
ex.
nums1 = [1, 2, 3, 0, 0, 0], nums2 = [1, 2, 3]
Output = [1, 1, 2, 2, 3, 3]
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Solution:
var merge = function(nums1, m, nums2, n) {
let count = 0
for (let i = m; i < (m + n); i++) {
nums1[i] = nums2[count]
count++
}
for (let j = 0; j < nums1.length - 1; j++) {
for (let k = j + 1; k < nums1.length; k++) {
if (nums1[j] > nums1[k]) {
let box = nums1[j]
nums1[j] = nums1[k]
nums1[k] = box
}
}
}
};
FlowChart:
Example 1
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
step.1 let i = m //3
i < (3 + 3) //3 < 6
nums1[3] = nums2[0] //[1,2,3,0,0,0] => [1,2,3,0,0,0]
2
count++ //1
i++ //4
i < (3 + 3) //4 < 6
nums1[4] = nums2[1] //[1,2,3,2,0,0] => [1,2,3,2,0,0]
5
count++ //2
i++ //5
i < (3 + 3) //5 < 6
nums1[5] = nums2[2] //[1,2,3,2,5,0] => [1,2,3,2,5,0]
6
count++ //3
step.2 nums1 = [1,2,3,2,5,6]
j = 0, j < 5
k = 0 + 1, k < 6 ... //k = 1, 2, 3, 4 ,5
nums1[0] > nums1[1] //1 < 2
nums1[0] > nums1[2] //1 < 3
nums1[0] > nums1[3] //1 < 2
nums1[0] > nums1[4] //1 < 5
nums1[0] > nums1[5] //1 < 6
j = 1
k = 1 + 1, k < 6 ... //k = 1, 2, 3, 4 ,5
nums1[1] > nums1[2] //2 < 3
nums1[1] > nums1[3] //2 < 2
nums1[1] > nums1[4] //2 < 5
nums1[1] > nums1[5] //2 < 6
j = 2
k = 2 + 1, k < 6 ... //k = 1, 2, 3, 4 ,5
nums1[2] > nums1[3] //3 < 2
box = nums1[2] = 3; nums1[2] = nums1[3] => 2; nums1[3] = box => 3
nums1 = [1,2,2,3,5,6]
nums1[2] > nums1[4] //2 < 5
nums1[2] > nums1[5] //2 < 6
j = 3
k = 3 + 1, k < 6 ... //k = 1, 2, 3, 4 ,5
nums1[3] > nums1[4] //3 < 5
nums1[3] > nums1[5] //3 < 6
j = 4
k = 4 + 1, k < 6 ... //k = 1, 2, 3, 4 ,5
nums1[4] > nums1[5] //5 < 6
nums1 = [1,2,2,3,5,6]
Blog:http://52.198.119.162/leetcode-js-88-merge-sorted-array/